package com.net.xpay.backend.job;

import com.net.common.concurrent.ThreadUtil;
import com.net.xpay.common.manager.notify.SafePayBatchNotifyRecordManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 拉取需要推送的数据
 */
@Slf4j
@Component
public class SafePayNotifyJob implements Runnable {

    @Autowired
    private SafePayBatchNotifyRecordManager safePayBatchNotifyRecordManager;


    private final LinkedBlockingQueue<Long> workQueue = new LinkedBlockingQueue<>();

    private final ConcurrentHashMap<Long, Integer> workMap = new ConcurrentHashMap<>();

    public SafePayNotifyJob() {
    }

    @Override
    public void run() {
        while (true) {
            try {
                doSelectedWaitNotifyRecord();
            } catch (Throwable e) {
                log.error("doSelectedWaitNotifyRecord", e);
            }
            ThreadUtil.safeSleep(10, "");
        }
    }

    private void doSelectedWaitNotifyRecord() {
        LocalDateTime maxNextNotifyTime = LocalDateTime.now();
        List<Long> ids = safePayBatchNotifyRecordManager.queryWaitNotifyRecord(10000, maxNextNotifyTime);

        for (Long id : ids) {
            Integer exist = workMap.putIfAbsent(id, 1);
            if (exist != null) {
                continue;
            }
            workQueue.add(id);
        }
    }

    public void remove(Long id) {
        workMap.remove(id);
    }

    public LinkedBlockingQueue<Long> getWorkQueue() {
        return workQueue;
    }
}
